//
//  StatusTableViewPictureView.swift
//  DSWeibo
//
//  Created by J on 16/4/30.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SDWebImage.UIImageView_WebCache

class StatusTableViewPictureView: UICollectionView {
    private let pictureViewCellID = "pictureViewCell"
    
    
    var status : Statuses?{
        didSet{
            reloadData()
        }
        
    }

    private let flowLayout  = UICollectionViewFlowLayout()

     init() {
        super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
        //注册cell
        self.registerClass(PictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellID)
        
        
        //注册cell
        dataSource = self
        delegate = self
        //设置cell间隙
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10

        
        //3.设置配图背景颜色
        //pictureView.backgroundColor = UIColor.purpleColor()
        

    }

    
    
    //计算微博配图的尺寸 包括单张和多张
    func calculateImageSize() -> (viewSize:CGSize, itemSize:CGSize){
        
        //1.取出配图的个数
        let count = status?.storePicURLS?.count
        
        //2.如果没有配图返回zero
        if count == 0 || count == nil {
            return (CGSizeZero,CGSizeZero)
        }
        //3.如果只有一张配图 返回图片的实际大小
        
        if count == 1 {
            let key = status?.storePicURLS!.first
            //3.1取出缓存图片
            let image =   SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key?.absoluteString)
            
            guard image != nil else {
                return (CGSizeZero,CGSizeZero)
            }
            flowLayout.itemSize = image.size
            //3.2返回缓存图片
            return (image.size,image.size)//图片大小 新浪后台已经计算好了
        }
        //4.如果有4张配图, 计算田字格大小
        let margin: CGFloat = 10.0
        let width = (UIScreen.mainScreen().bounds.size.width - 40 - 2.0*margin)/3
        
        flowLayout.itemSize = CGSize(width: width, height: width)
        
        if count == 4 {
            let viewWidth = width * 2 + margin
            let viewHeight = viewWidth
            return (CGSize(width: CGFloat(viewWidth), height: CGFloat(viewHeight)),CGSize(width: CGFloat(viewWidth), height: CGFloat(viewHeight)))
        }
        
        
        //5.如果是其他(多张)计算九宫格大小
        
        //2 3 5 6 7 8 9
        //5.1计算列数
        let colNumber:CGFloat = 3
        //5.2计算行数
        let rowNumber  = CGFloat(ceilf(Float(count!)/3.0))
        //宽度 = 列数 * 图片宽度 + (列数-1)*间隙
        let viewWidth = colNumber * width + (colNumber - 1)*margin
        //高度 = 行数 * 图片高度 + (行数-1)*间隙
        let viewHeight = rowNumber * width + (rowNumber - 1)*margin
        
        return (CGSize(width: viewWidth, height: viewHeight),CGSize(width: viewWidth, height: viewHeight))
        
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    //private 在同一个文件中是可以互相访问的
    private class PictureViewCell: UICollectionViewCell {
        
        // 定义属性接收外界传入的数据
        var imageURL: NSURL?
            {
            didSet{
                self.gifImageView.hidden = true
                iconImageView.sd_setImageWithURL(imageURL!)
                if imageURL!.absoluteString.lowercaseString.hasSuffix("gif") {//全部转换为小写进行对比
                    print(imageURL)
                    self.gifImageView.hidden = false

                }
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            // 初始化UI
            setupUI()
        }
        
        private func setupUI()
        {
            // 1.添加子控件
            contentView.addSubview(iconImageView)
            iconImageView.addSubview(gifImageView)
            // 2.布局子控件
            iconImageView.snp_makeConstraints { (make) in
                make.edges.equalTo(contentView)
            }
            
            gifImageView.snp_makeConstraints { (make) in
                make.bottom.equalTo(iconImageView)
                make.right.equalTo(iconImageView)
                make.size.equalTo(gifImageView.image!.size)
            }
            
            
        }
        
        // MARK: - 懒加载
        private lazy var iconImageView:UIImageView = UIImageView()
        
        //gif
        private lazy var gifImageView:UIImageView = {
            let gif = UIImageView(image: UIImage(named: "avatar_grassroot"))
            gif.hidden = true
            return gif
        }()
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
    }

    

    
}

//选中图片通知名称
let StatusTableViewPictureViewSelected = "StatusTableViewPictureViewSelected"//当前选中图片索引key
let StatusTableViewPictureViewIndexKey = "StatusTableViewPictureViewIndexKey"//选中图片通知名称
let StatusTableViewPictureViewURLKey   = "StatusTableViewPictureViewURLKey"//需要展示的所有图片对应key

extension StatusTableViewPictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.storePicURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //1.取出cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellID, forIndexPath: indexPath) as! PictureViewCell
        
        cell.imageURL = status?.storePicURLS![indexPath.item]
        //2.设置数据
        //        cell.backgroundColor = UIColor.orangeColor()
        //3.返回cell
        return cell
        
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        print(status?.storeMiddlPicURLS?[indexPath.item])
        
        
        NSNotificationCenter.defaultCenter().postNotificationName(StatusTableViewPictureViewSelected, object: self, userInfo: [StatusTableViewPictureViewIndexKey:indexPath,StatusTableViewPictureViewURLKey:(status?.storeMiddlPicURLS)!])
    }
    
    
}









     